/*
 * Created by: Peter Weissbrod
 * Created: Saturday, November 03, 2007
 */
using System;
using EntityLayer.Entities;
using Utils;

namespace Controllers
{
    public class UserController : ControllerBase<User>
    {
        #region methods
        public UserController(IUserManagementView userManagementView) : base(userManagementView)
        {
            userManagementView.CreateUserEvent += new EventHandler<UserEventArgs>(userManagentView_CreateUserEvent);
            userManagementView.UpdateUserEvent += new EventHandler<UserEventArgs>(userManagentView_UpdateUserEvent);
        }
        private void userManagentView_UpdateUserEvent(object sender, UserEventArgs e)
        {
            User user = e.User;
            Check.Assert(user.UserID != Nulls.ID);
            ValidateData(user);
            user.UpdateAndFlush();
        }
        private void userManagentView_CreateUserEvent(object sender, UserEventArgs e)
        {
            User user = e.User;
            Check.Assert(user.UserID == Nulls.ID, "UserID is populated... this should not be!");
            ValidateData(user);
            user.Save();
        }
        #endregion

        /// <summary>
        /// If the incoming data is invalid, an exception will be thrown here
        /// </summary>
        /// <param name="t"></param>
        protected override void ValidateData(User user)
        {
            Check.Assert(user.UserName != Nulls.String, "UserName is Required");
            Check.Assert(user.PasswordHash != Nulls.String, "Password is required");
            Check.Assert(
                User.FindAllByProperty("UserName", user.UserName).Length == 0, "This username is already in use"
                );
        }
    }
}